import 'package:casdon/app/config/theme/theme_extention.dart';
import 'package:casdon/build_gen/assets.gen.dart';
import 'package:casdon/common/utils/string_externtion.dart';
import 'package:casdon/common/widget/common_loading_widget.dart';
import 'package:casdon/modules/me/application/notification/browsing_recipe_history_notifier.dart';

import 'package:casdon/modules/me/data/model/browsing_recipe_history_model.dart';
import 'package:casdon/auto_router.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

/// 菜谱浏览记录子页面
class BrowsingRecipeHistoryScreen extends ConsumerWidget {
  const BrowsingRecipeHistoryScreen({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final state = ref.watch(browsingRecipeHistoryNotifierProvider);
    final notifier = ref.read(browsingRecipeHistoryNotifierProvider.notifier);

    return RefreshIndicator(
      onRefresh: () => notifier.refresh(),
      child: NotificationListener<ScrollNotification>(
        onNotification: (notification) {
          if (notification is ScrollEndNotification &&
              notification.metrics.pixels >=
                  notification.metrics.maxScrollExtent - 50) {
            notifier.loadMore();
          }
          return false;
        },
        child: state.when(
          loading: () => const Center(child: CommonLoadingWidget()),
          error: (e, _) => Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text('加载失败'),
                const SizedBox(height: 16),
                ElevatedButton(
                  onPressed: () => notifier.refresh(),
                  child: const Text('重试'),
                ),
              ],
            ),
          ),
          data: (historyState) {
            if (historyState.data.isEmpty) {
              return _buildEmptyState(context);
            }

            final grouped = historyState.groupedByDate;

            return ListView.builder(
              padding: EdgeInsets.symmetric(vertical: 8.h),
              itemCount: grouped.length,
              itemBuilder: (context, dateIndex) {
                final dateEntry = grouped.entries.elementAt(dateIndex);
                final date = dateEntry.key;
                final items = dateEntry.value;

                return Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // 日期标题
                    Padding(
                      padding: EdgeInsets.symmetric(
                        horizontal: 16.w,
                        vertical: 8.h,
                      ),
                      child: Row(
                        children: [
                          Container(
                            width: 10.w,
                            height: 10.w,
                            decoration: BoxDecoration(
                              color: context.colorScheme.primary,
                              shape: BoxShape.circle,
                            ),
                          ),
                          SizedBox(width: 8.w),
                          Text(
                            date,
                            style: context.textTheme.bodyMedium!.copyWith(
                              color: context.customColorThemeNonNull.textColor3,
                            ),
                          ),
                        ],
                      ),
                    ),
                    // 列表项
                    ...items.map((item) => _buildHistoryItem(context, item)),
                  ],
                );
              },
            );
          },
        ),
      ),
    );
  }

  Widget _buildHistoryItem(
    BuildContext context,
    BrowsingRecipeHistoryModel item,
  ) {
    return InkWell(
      onTap: () {
        // 跳转到菜谱详情
        RecipeDetailRoute(
          recipeId: item.id,
          title: item.title,
          isSmart: item.isSmart,
        ).push(context);
      },
      child: Container(
        margin: EdgeInsets.symmetric(horizontal: 12.w, vertical: 4.h),
        padding: EdgeInsets.all(6.w),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(8),
        ),
        child: Row(
          children: [
            // 图片
            ClipRRect(
              borderRadius: BorderRadius.circular(6),
              child: CachedNetworkImage(
                imageUrl: item.mainImg.cropParams700,
                width: 64.w,
                height: 64.w,
                fit: BoxFit.cover,
                placeholder: (context, url) => Container(
                  width: 64.w,
                  height: 64.w,
                  color: Colors.grey[200],
                ),
                errorWidget: (context, url, error) => Container(
                  width: 64.w,
                  height: 64.w,
                  color: Colors.grey[200],
                  child: Icon(Icons.image_outlined, color: Colors.grey[400]),
                ),
              ),
            ),
            SizedBox(width: 12.w),
            // 标题
            Expanded(
              child: Text(
                item.title,
                style: context.textTheme.bodyMedium!.copyWith(
                  color: context.customColorThemeNonNull.textColor1,
                ),
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildEmptyState(BuildContext context) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Image(
            image: Assets.images.emptyData.provider(),
            width: 106.w,
            height: 68.w,
          ),
          SizedBox(height: 16.h),
          Text(
            "暂无数据",
            style: context.textTheme.bodyMedium!.copyWith(
              color: context.customColorThemeNonNull.textColor2,
            ),
          ),
        ],
      ),
    );
  }
}
